//
//  CirleListViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 3/6/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import UITableView_FDTemplateLayoutCell
import SVProgressHUD
import MJRefresh
import AVOSCloud

class CircleListViewController: RootViewController,UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var topNumLabel: UILabel!
    @IBOutlet weak var replyNumLabel: UILabel!
    @IBOutlet weak var moderatorButton: UIButton!
    
    
    
    var city: City?
    var topArray = [Topic]()
    var commArray = [Topic]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = city?.name
        
        userImageView.layer.cornerRadius = 5
        userImageView.layer.masksToBounds = true
        
        moderatorButton.setTitle("", for: UIControlState())
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { 
            self.rquestData(true)
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.rquestData(false)
        })
        rquestData(true)
         NotificationCenter.default.addObserver(self, selector: #selector(CircleListViewController.refreshData(_:)), name: NSNotification.Name(rawValue: kNotificationRefreshCircleListView), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        userImageView?.kf.setImage(with: URL(string: (city?.iconImage?.url)!)!,
                               placeholder: DataCenter.sharedInstance.placeholderImage,
                               options: nil,
                               progressBlock: { receivedSize, totalSize in
                                
            },
                               completionHandler: { image, error, cacheType, imageURL in
                                
        })
        
        topNumLabel.text = "\(city!.topicCount)"
        replyNumLabel.text = "\(city!.replyCount)"
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func refreshData(_ noti: Notification) {
        rquestData(true)
    }
    
    func rquestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Topic.query()
        query.includeKey(kTopicKeyContentImage)
        query.includeKey(kTopicKeyUser)
        query.whereKey(kTopicKeyCitys, equalTo: city)
        query.order(byDescending: kTopicKeyLastReplyTime)
        query.limit = kNetPageSize
        if !header {
            let top = commArray.last
            let date = top?.object(forKey: kTopicKeyLastReplyTime)
            if date != nil {
                query.whereKey(kTopicKeyLastReplyTime, lessThan: date)
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            
            if error == nil && objects != nil {
                if let topic = objects as? [Topic] {
                    if header {
                        self.topArray.removeAll()
                        self.commArray.removeAll()
                    }
                    for top in topic {
                        if top.isInTop {
                            self.topArray.append(top)
                        } else {
                            self.commArray.append(top)
                        }
                    }
                    self.tableView.reloadData()
                    SVProgressHUD.dismiss()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
            self.tableView.mj_header.endRefreshing()
            if objects != nil && (objects?.count)! < kNetPageSize {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                
            } else {
                if header {
                    self.tableView.mj_footer.resetNoMoreData()
                } else {
                    self.tableView.mj_footer.endRefreshing()
                }
            }
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return topArray.count
        }
        return commArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath as NSIndexPath).section == 0 {
           return 38
        }
        return tableView.fd_heightForCell(withIdentifier: "CircleListCommonCell", configuration: { (cell: Any?) in
            let commonCell = cell as? CircleListCommonCell
            let topic = self.commArray[(indexPath as NSIndexPath).row] 
            commonCell!.refreshView(topic)
        })
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath as NSIndexPath).section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CircleListTopCell", for: indexPath) as! CircleListTopCell
            let topic = topArray[(indexPath as NSIndexPath).row]
            cell.refreshView(topic)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CircleListCommonCell", for: indexPath) as! CircleListCommonCell
            let topic = commArray[(indexPath as NSIndexPath).row] 
            cell.refreshView(topic)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//        let topic: Topic?
//        if indexPath.section == 0 {
//            topic = topArray[indexPath.row]
//        } else {
//            topic = commArray[indexPath.row]
//        }
//        topic!.incrementKey(kTopicKeyClickCount)
//        topic!.fetchWhenSave = true
//        topic!.saveInBackground()
    }
    
    @IBAction func sendTopClicked(_ sender: UIBarButtonItem) {
        if AVUser.current() == nil { // 没登录
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController");
            self.navigationController?.pushViewController(loginViewController, animated: true)
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let sendTopVC = storyboard.instantiateViewController(withIdentifier: "SendTopicViewController") as! SendTopicViewController;
            sendTopVC.city = city
             self.navigationController?.pushViewController(sendTopVC, animated: true)
        }
    }
   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "CirclReplyViewController" {
            
            let replyVC = segue.destination as! CirclReplyViewController
            replyVC.city = city
            
            let cell = sender as! UITableViewCell
            if let indexPath = tableView.indexPath(for: cell) {
                if (indexPath as NSIndexPath).section == 0 {
                   let topic = topArray[(indexPath as NSIndexPath).row]
                    replyVC.topic = topic
                } else {
                   let topic = commArray[(indexPath as NSIndexPath).row]
                    replyVC.topic = topic
                }
            }
        }
    }
}
